<?php
//商铺管理
namespace App\Http\Controllers\App;
use App\Http\Controllers\App\BaseController as Controller;
use App\Models\ShopDish;
use App\Models\ShopDishAttribute;
use App\Tools\Map;
use function foo\func;
use Illuminate\Http\Request;
use App\Models\Shop;
use App\Models\City;
use App\Models\ShopInfo;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class ManagementShop extends Controller
{
    protected $thisLoginClerk;
    public function __construct(Request $request)
    {
        $checkThisClerk = $this->getShopUserID($request->token,$request->device_id);
        if(!$checkThisClerk){
            return show(2001,'无效token');
        }else{//判断用户角色
            //权限处理
            switch($checkThisClerk->role){
                case -1:
                    $this->thisLoginClerk = $checkThisClerk;
                    break;
                case 0:
                case 1:
                case 2:
                case 3:
                    return show(2002,'没有权限');
                    break;
                default:
                    return show(2002,'没有权限');
                    break;
            }
        }
    }
    //新建商铺
    public function createShop(Request $request)
    {
        $rules = [
            'shop_name' => 'required|min:1',
            'shop_address'=>'required|min:3',
            'shop_pic'=>'required',
            'shop_phone' => 'required|mobile',
            'lience_pic'=>'required',
            'opentime'=>'required',
            'note'=>'string|min:3|max:100',
            'name'=>'required|string',
            'shop_avatar'=>'required|string',
            'business_code'=>'integer',
            'is_takeout'=>'integer|in:0,1',
            'is_reserve'=>'integer|in:0,1',
            'is_list'=>'integer|in:0,1',
            'type_id'=>'integer|exists:shop_types,id'
        ];
        $message = [
            'shop_name.*'=>'请填写认真店铺名称',
            'shop_address.*'=>'请认真填写店铺地址',
            'shop_phone.*'=>'联系方式有误',
            'shop_pic.*'=>'请上传店铺照片',
            'lience_pic.*'=>'请上传营业执照',
            'opentime.*'=>'请认证填写营业时间',
            'name.*'=>'请填写店主姓名',
            'shop_avatar.*'=>'请上传商家头像',
            'business_code.*'=>'商圈填写有误',
            'type_id.*'=>'选取的分类信息有误',
            'is_takeout.*'=>'请确定是否选择外卖',
            'is_reserve.*'=>'请确定是否选择预定',
            'is_list.*'=>'请确定是否选择排队点餐',
            'note.string'=>'请填写商家介绍',
            'note.min'=>'商家介绍太长了',
            'note.max'=>'商家介绍太长了'
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(2003,$validator->errors()->first());
        }
        $latng = Map::getLngLat(\request('shop_address'));
        if (empty($latng)){
            return show(201,'经纬度不存在',[
                "shop_address"=>["注意: shop address 填写有误，请重新填写."]
            ]);
        }
        $latitude = $latng['lat'];
        $longitude = $latng['lng'];
        $user_id = $this->thisLoginClerk->shop_user_id;
        $data = array_merge(
            \request(['shop_phone','is_takeout','is_reserve','is_list','shop_name','shop_address','shop_pic','lience_pic','note','name','shop_avatar','business_code']),
            compact('user_id','longitude','latitude')
        );
        // 后期添加使用
//        $count = Shop::where('user_id',$user_id)->count();
//        if ($count>=5){
//            return show(201,'平台仅支持每个账号拥有五个商家！');
//        }
        $contact = \request('shop_phone');
        DB::beginTransaction();
        try{
            $res1 = Shop::create($data);
            $shop_id = $res1->id;
            $created_at = date("Y-m-d H:i:s");
            $opentime = preg_replace('# #','',$request->opentime);
            $info_data =array_merge(
                ['opentime'=> $opentime,'type_id'=>$request->type_id],
                compact('shop_id','contact','created_at')
            );
            $res2 = DB::table('shop_info')->insert($info_data);//ShopInfo::create($info_data);
            if ($res1 && $res2){
                DB::commit();
                return show(200,'店铺创建成功，请耐心等待审核！');
            }
        }catch (\Exception $e){
            DB::rollBack();
//            dd($e->getMessage());
            return show(203,'请重新提交资料或联系客服');
        }
    }

    // 获取所有商家的信息
    public function showAllShops()
    {
        $user_id = $this->thisLoginClerk->shop_user_id;
        $shop = Shop::where('user_id',$user_id)
            ->get(['id','shop_avatar','note','shop_name','is_check']);
        if ($shop->isNotEmpty()){
            foreach ($shop as $sh){
                $shopinfo = ShopInfo::where('shop_id',$sh->id)->first();
                if ($shopinfo){
                    $sh['is_open'] = $shopinfo->is_open;
                }else{
                    $sh['is_open'] = 0;
                }

            }
        }

        return show(200,'所有商家信息',$shop);
    }
    //修改商铺资料
    public function showEditShop(Request $request)
    {
        $rules = [
            'shop_id' => 'required|exists:shops,id',
        ];
        $message = [
            'shop_id.*'=>'商家信息有误'
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(2003,$validator->errors()->first());
        }
        $now_role = $this->thisLoginClerk->role;
        if ($now_role == '-1'){         // 商家
            // 判断这个商铺是否属于该商家
            $user_id = $this->thisLoginClerk->id;
            if (!Shop::checkIsShop($request->shop_id,$user_id)){
                return show(2002,'没有权限');
            }
        }else{// 服务员
            // 判断这个商铺是否属于当前服务员的商铺
            if( $request->shop_id != $this->thisLoginClerk->shop_id){
                return show(2002,'没有权限');
            }
        }
        try{
            $shop = Shop::find($request->shop_id);
            $info = ShopInfo::where('shop_id',$request->shop_id)->first();
            if ($shop && $info){
                $shop = array_merge($shop->toArray(),$info->toArray());
            }else{
                return show(2002,'没有权限');
            }

            //返回商圈数据
            $shop['trade_area'] = City::find($shop['business_code']);
//
            return show(200,'商家信息',$shop);
        }catch (\Exception $e){
//            dd($e->getMessage());
            return show(2002,'没有权限');
        }


    }

    public function deleteShop(Request $request){

        $rules = [
            'shop_id' => 'required|exists:shops,id',
        ];
        $message = [
            'shop_id.*'=>'商家信息有误'
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(201,$validator->errors()->first());
        }
        DB::beginTransaction();
        try{
            $shop = DB::table('shops')->find($request->shop_id);
            $shop_id = $shop->id;
            $res1 = Shop::where('id',$request->shop_id)->delete();

            $res2 = ShopInfo::where('shop_id',$shop_id)->delete();
            $allDish = ShopDish::where('shop_id',$shop_id)->get();
            if ($allDish->isNotEmpty()){
                foreach ($allDish as $one){
                    ShopDish::where('shop_id',$shop_id)->where('id',$one->id)->delete();
                    ShopDishAttribute::where('dish_id',$one->id)->delete();
                }
            }
            if ($res1 && $res2){
                DB::commit();
                return show(200,'删除成功');
            }else{
                DB::rollBack();
                return show(204,'请重新操作或联系客服');
            }
        }catch (\Exception $e){
//            dd($e->getMessage());
            DB::rollBack();
            return show(204,'请重新操作或联系客服');
        }
    }
    // 修改商铺资料
    public function editShop(Request $request){
        $rules = [
            'shop_name' => 'required',
            'shop_address'=>'required|min:3',
            'shop_phone' => 'required',
            'shop_pic'=>'required',
            'lience_pic'=>'required',
            'opentime'=>'required',
            'shop_id' => 'required|exists:shops,id',
            'note'=>'string|min:3|max:100',
            'name'=>'required|string',
            'shop_avatar'=>'required',
            'business_code'=>'integer',
            'is_takeout'=>'integer|in:0,1',
            'is_reserve'=>'integer|in:0,1',
            'is_list'=>'integer|in:0,1',
            'type_id'=>'integer|exists:shop_types,id'
        ];
        $message = [
            'shop_phone.*'=>'联系方式有误',
            'shop_name.*'=>'店铺名称有误',
            'shop_address.*'=>'店铺地址有误',
            'shop_pic.*'=>'请上传店铺照片',
            'lience_pic.*'=>'请上传营业执照',
            'opentime.*'=>'请认真填写营业时间',
            'shop_id.*'=>'商家信息有误',
            'name.*'=>'商家信息有误',
//            'note.*'=>'商家信息有误',
            'shop_avatar.*'=>'商家头像有误',
            'business_code.*'=>'商圈选择有误',
            'type_id.*'=>'选取的分类信息有误',
            'is_takeout.*'=>'请确定是否选择外卖',
            'is_reserve.*'=>'请确定是否选择预定',
            'is_list.*'=>'请确定是否选择排队点餐',
            'note.string'=>'请填写商家介绍',
            'note.min'=>'商家介绍太长了',
            'note.max'=>'商家介绍太长了'
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(2003,$validator->errors()->first());
        }
        $latng = Map::getLngLat(\request('shop_address'));
        if (empty($latng)){
            return show(2003,'经纬度不存在',[
                "shop_address"=>["注意: shop address 填写有误，请重新填写."]
            ]);
        }
        $latitude = $latng['lat'];
        $longitude = $latng['lng'];
        $data = array_merge(
            \request(['shop_phone','shop_name','is_takeout','is_reserve','is_list','shop_address','shop_pic','lience_pic','note','name','business_code','shop_avatar']),
            compact('longitude','latitude')
        );

        $contact = \request('shop_phone');
        DB::beginTransaction();
        try{
            Shop::where('id',$request->shop_id)->update($data);
            $opentime = preg_replace('# #','',$request->opentime);
            $info_data =array_merge(
                ['opentime'=> $opentime,'type_id'=>$request->type_id],
                compact('contact')
            );
            DB::table('shop_info')->where('shop_id',$request->shop_id)->update($info_data);
            DB::commit();
            return show(200,'修改成功');
        }catch (\Exception $e){
            DB::rollBack();
            return show(201,'请重新提交资料或联系客服');
        }
    }

    // 上传商家图片
    public function upload(Request $request){
        header("Content-Type: text/html; charset=utf-8");
        if($_FILES['thumb']['size'] == 0 || $_FILES['thumb']['size']>1024*1024) {
            return show(201, '请上传1M以内的图片');
        }
        $rules = [
            'thumb'=>'required|image',
        ];
        $message = [
            'thumb.*' => '请上传图片'
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(201,$validator->errors()->first());
        }
        $type = $request->file('thumb')->getClientOriginalExtension();
        if (!in_array($type,['jpg','jpeg','png'])){
            return show(201,'请上传png|jpg|jpeg格式的图片');
        }
        $user_id = $this->thisLoginClerk->shop_user_id;
        $path = $request->file('thumb')->storePublicly("user_{$user_id}/info");
        return show(200,'上传成功','/storage/'. $path);
    }
    // 商家是否营业
    public function shopOpen(Request $request){
        try{
            $rules = [
                'id'=>'required|integer|exists:shops,id',
                'is_open'=>'required|in:0,1'
            ];
            $message = [
                'id.*'=> '商家信息不合法',
                'is_open.*'=>'营业状态不合法'
            ];
            $validator = Validator::make($request->all(), $rules,$message);
            if ($validator->fails()) {
                return show(2003,$validator->errors()->first());
            }
            $shop_id = $request->id;
            $is_open = $request->is_open;
            $result = ShopInfo::where('id',$shop_id)->update(['is_open'=>$is_open]);
            $shopinfo = ShopInfo::where('id',$shop_id)->first();
            $now_status = $shopinfo->is_open;
            return show(200,'更新成功',['is_open'=>$now_status]);
        }catch (\Exception $e){
            return show(201,'更新失败',['is_open'=>$now_status]);
        }

    }


}
